package com.nervenets.web.controller.tags;

import com.nervenets.web.controller.BaseController;
import com.nervenets.web.controller.IdParams;
import com.nervenets.web.entity.KeyValue;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.entity.ResponseResult;
import com.nervenets.web.hibernate.dao.TagsDao;
import com.nervenets.web.hibernate.domain.knowledge.Tags;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Api(value = "标签接口v1", description = "标签相关接口")
@RestController
@RequestMapping("/api/v1/tags")
public class TagsController extends BaseController {
    @Resource
    private TagsDao tagsDao;

    @ApiOperation("查看标签详情")
    @PostMapping("/detail")
    public ResponseResult detail(@RequestBody IdParams params) {
        final Set<ConstraintViolation<IdParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }
        final Tags object = tagsDao.findById(params.getTargetId()).orElse(null);
        if (null == object) return errorMessage(MessageCode.code_404, "您查看的标签不存在");
        return successMessage(object);
    }

    @ApiOperation("标签新建或修改")
    @PostMapping("/edit")
    public ResponseResult edit(@RequestBody TagsEditParams params) throws Exception {
        if (params.tokenIllegal()) return errorMessage(MessageCode.code_777);
        final Set<ConstraintViolation<TagsEditParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        Tags tags = new Tags();
        if (params.getTagsId() > 0) {
            tags = tagsDao.findById(params.getTagsId()).orElse(null);
            if (null == tags) return errorMessage(MessageCode.code_404, "您修改的标签不存在");
        }
        tags.setManagerId(params.getManagerId());
        tags.setName(params.getName());
        tags.setEnable(params.isEnable());
        tags.setWeight(params.getWeight());
        tagsDao.save(tags);

        return successMessage(tags);
    }

    @ApiOperation("标签列表")
    @PostMapping("/list")
    public ResponseResult list(@RequestBody TagsPagingParams params) {
        final Set<ConstraintViolation<TagsPagingParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        Specification<Tags> specification = (Specification<Tags>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("removed"), 0));
            if (params.getManagerId() > 0) {
                predicates.add(criteriaBuilder.equal(root.get("managerId"), params.getManagerId()));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<Tags> page = tagsDao.findAll(specification, PageRequest.of(params.getPage(), params.getLimit(), new Sort(Sort.Direction.DESC, "weight")));
        return successMessage(page.getContent(), new KeyValue("page", params.getPage()), new KeyValue("total", page.getTotalElements()));
    }

    @ApiOperation("所有标签列表，targetId传团队ID")
    @PostMapping("/all")
    public ResponseResult all(@RequestBody IdParams params) {
        return successMessage(tagsDao.findAllByManagerIdAndEnableIsTrueOrderByWeightDesc(params.getTargetId()));
    }
}
